package com.kehongborui.fliggy.aop;

import com.kehongborui.fliggy.entity.User;
import com.kehongborui.fliggy.service.impl.OrderServiceImpl;
import com.kehongborui.fliggy.util.JedisUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-09-11
 */
@Component
@Aspect
public class CacheAspect {
    @Autowired
    private JedisUtil jedisUtil;

    @Around("execution (* com.kehongborui.fliggy.service..*(..))")
    public Object handler(ProceedingJoinPoint pjp) throws Throwable {
        // 获取被执行的方法名称
        if (pjp.getTarget().getClass().equals(OrderServiceImpl.class) && "findById".equals(pjp.getSignature().getName())) {
            Object[] args = pjp.getArgs();
            // 从缓存中获取用户信息
            Object user = jedisUtil.getObject((String) (args[0]), User.class);
            if (user == null) {
                user = pjp.proceed();
                // 将从数据库获取的数据放到缓存
                jedisUtil.setObject((String) (args[0]), user);
            }

            // 返回用户信息
            return user;

        } else {
            return pjp.proceed();
        }
    }
}
